package com.tensquare.spit.controller;

import com.tensquare.spit.pojo.Spit;
import com.tensquare.spit.service.SpitService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by WF on 2020/3/31 15:32
 */
@RestController
@RequestMapping("spit")
public class SpitController {
    @Autowired
    private SpitService spitService;
    @Autowired
    private RedisTemplate redisTemplate;
    //1.查询吐槽列表
    @GetMapping
    public Result findAll(){
        //1.1)查询所有的吐槽列表
        List<Spit> spits = spitService.findAll();
        //1.2)返回
        return new Result(true,StatusCode.OK,"查询吐槽列表成功！",spits);
    }
    //2.根据id查询吐槽
    @GetMapping("{spitId}")
    public Result findById(@PathVariable String spitId){
        //2.1)根据id查询吐槽对象
        Spit spit = spitService.findOne(spitId);
        //2.2)返回
        return new Result(true,StatusCode.OK,"查询单个吐槽成功！",spit);
    }
    //3.添加吐槽
    @PostMapping
    public Result add(@RequestBody Spit spit){
        //3.1)添加吐槽
        spitService.insert(spit);
        //3.2)返回
        return new Result(true,StatusCode.OK,"添加吐槽成功！");
    }
    //4.修改吐槽
    @PutMapping("{spitId}")
    public Result update(@PathVariable String spitId,@RequestBody Spit spit){
        //关联id
        spit.set_id(spitId);
        //修改吐槽
        spitService.update(spit);
        //返回
        return new Result(true,StatusCode.OK,"修改吐槽成功！");
    }
    //5.删除吐槽
    @DeleteMapping("{spitId}")
    public Result delete(@PathVariable String spitId){
        //5.1)删除吐槽
        spitService.delete(spitId);
        //5.2)返回
        return new Result(true,StatusCode.OK,"删除吐槽成功！");
    }
    //6.吐槽点赞
    @PutMapping("thumbup/{spitId}")
    public Result thumbup(@PathVariable String spitId){
        //6.1）避免重复点赞
        //6.1.1)从redis中取得标记
        Object flag = redisTemplate.opsForValue().get("thumbup_" + spitId);
        //6.1.2)如果此标记存在，就证明点赞过
        if(flag != null){
            return new Result(false,StatusCode.ERROR,"不能重复点赞！");
        }
        spitService.thumbup2(spitId);
        //6.1.3）点赞成功后就将标记写到redis中
        redisTemplate.opsForValue().set("thumbup_"+spitId,"1");

        return new Result(true,StatusCode.OK,"吐槽点赞成功！");
    }
    //7.根据上级id查询吐槽数据
    @GetMapping("comment/{parentid}/{page}/{size}")
    public Result comment(@PathVariable String parentid,@PathVariable int page,@PathVariable int size){
        //7.1)查询上级id对应的列表
        PageResult pageResult = spitService.comment(parentid,page,size);
        //7.2)返回
        return new Result(true,StatusCode.OK,"根据父id查询吐槽列表!",pageResult);
    }
}
